package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import common.util.DateTimeUtils;

import entity.ImageInfo;


public class ImageInfoDao {

	private static ImageInfoDao instance;
	private BaseDao baseDao;

	protected ImageInfoDao() {
		this.baseDao = BaseDao.getInstance();
	}

	public static ImageInfoDao getInstance() {
		if (instance == null) {
			instance = new ImageInfoDao();
		}
		return instance;
	}
	
	public void saveNewImageInfo(ImageInfo imageInfo){
		String dateTaken = DateTimeUtils.toTimeStampString(imageInfo.getDateTaken());
		//String query  = "INSERT INTO image_info (FILE_NAME, TITLE, DATE_TAKEN) VALUES (?,?,?)";
		String query  = "INSERT INTO image_info (ID, FILE_NAME, TITLE, DATE_TAKEN, FILE_TYPE) VALUES ('"  
				+ imageInfo.getId() +"', '" + imageInfo.getFileName()+"', '"  
				+ imageInfo.getTitle() +"', '"+dateTaken + "', '" + imageInfo.getFileType() +"')";
		
		try {
			/*java.sql.PreparedStatement preparedStatement = baseDao.getConnection().prepareStatement(query);
			preparedStatement.setString(1,imageInfo.getFileName());
			preparedStatement.setString(2, imageInfo.getTitle());
			preparedStatement.setTimestamp(3, new Timestamp(imageInfo.getCreateDate().getTime()));*/
			
			//imageInfo.setId((long) preparedStatement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS));
			 baseDao.executeUpdate(query);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public List<ImageInfo> getListImageInfo(String condition) throws Exception{
		String query = "SELECT * FROM image_info";
		if(condition != null && !"".equals(condition)) {
			query = query + " " + condition;
		}
		ResultSet rs = baseDao.executeQuery(query);
		List<ImageInfo> imageInfos = new ArrayList<ImageInfo>();
		while (rs.next()) {
			ImageInfo object = new ImageInfo(rs.getString("ID"),
					rs.getString("FILE_NAME"), 
					rs.getString("TITLE"),
					rs.getString("AUTHOR"), 
					rs.getInt("RATING"),
					rs.getString("TAGS"), 
					rs.getDate("DATE_TAKEN"),
					rs.getString("FILE_TYPE"), 
					rs.getLong("COMMENT_ID"),
					rs.getString("STORE_PATH"), 
					rs.getString("CAMERA_MAKER"), 
					rs.getDate("CREATE_DATE"),
					rs.getString("CREATE_BY"),
					rs.getDate("MODIFY_DATE"),
					rs.getString("MODIFY_BY"),
					rs.getInt("STATUS"));
			imageInfos.add(object);
		}

		return imageInfos;
	}
}
